<?php
declare (strict_types = 1);

namespace app\common\model\Post;

use app\common\model\Config;
use think\Model;
use think\model\concern\SoftDelete;

/**
 * @mixin \think\Model
 */
class Post extends Model
{

    // 使用软删除
    use SoftDelete;

    // 帖子表
    protected $table = 'pre_post';

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;

    // 定义创建时间
    protected $createTime = 'createtime';

    // 定义更新时间
    protected $updateTime = false;

    // 软删除字段
    protected $deleteTime = 'deletetime';

    protected $append = [
        'comment_count',
        'state_text',
        'visit_count'
    ];

    // 查询帖子状态
    public function state()
    {
        /* 
            [25 => '置顶']
            [
                [
                    point => 25,
                    name => '置顶'
                ]
            ]
        */

        // 查询配置表的数据
        $PostState1 = Config::where(['key' => 'PostState1'])->value('value');
        $PostState2 = Config::where(['key' => 'PostState2'])->value('value');
        $PostState3 = Config::where(['key' => 'PostState3'])->value('value');

        return [1 => "置顶 {$PostState1}积分",2 => "精华 {$PostState2}积分", 3 => "热门 {$PostState3}积分"];
    }

    // 关联查询
    public function user()
    {
        return $this->belongsTo('app\common\model\User\User','userid','id');
    }

    public function type()
    {
        return $this->belongsTo('app\common\model\Post\Cate','cateid','id');
    }

    // 查询所有帖子评论量 => 模型获取器
    public function getCommentCountAttr($value,$data)
    {
        $Count = Comment::where(['postid' => $data['id']])->count();

        return $Count;
    }

    // 状态
    public function getStateTextAttr($value,$data)
    {
        $StateList = [0 => '常规', 1 => '置顶', 2 => '精华', 3 => '热门'];

        return $StateList[$data['state']];
    }

    // 浏览量
    public function getVisitCountAttr($value,$data)
    {
        $visit = $data['visit'] ? explode(',',$data['visit']) : [];

        return count($visit);
    }
}


